<template>
  <div class="app-container">
    <!-- 导航栏 -->
    <div class="nav">
      <router-link to="/dashboard/dash" class="nav-link"><span>首页</span></router-link>
      <router-link :to="{ 
        name: 'Dashboard',
        params: { 
          standardName: staName 
        }
      }" class="nav-link">
        <span>/</span><span>{{ staName }}</span>
      </router-link>
      <span>/</span><span class="current-page">项目管理</span>
      <div class="nav-back">
        <el-button type="text" @click="handleBack">
          <i class="el-icon-arrow-left"></i> 返回
        </el-button>
      </div>
    </div>

    <!-- 搜索框和按钮 -->
    <div class="search-buttons-container">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入搜索关键字"
        prefix-icon="el-icon-search"
        clearable
      ></el-input>
      <div class="button-group">
        <el-button type="danger" @click="batchDelete" :disabled="!multipleSelection.length">
          <i class="el-icon-delete"></i> 批量删除
        </el-button>
        <el-button type="primary" @click="showDialog">
          <i class="el-icon-plus"></i> 添加
        </el-button>
        <el-button type="success" @click="exportExcel">
          <i class="el-icon-download"></i> 导出Excel
        </el-button>
        <el-button type="warning" @click="importExcel">
          <i class="el-icon-upload2"></i> 导入Excel
        </el-button>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog title="添加项目" :visible.sync="dialogVisible">
      <el-form :model="form">
        <el-form-item label="项目名称" :label-width="formLabelWidth">
          <el-input v-model="form.pjName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="标准编号（含年号）" :label-width="formLabelWidth">
          <el-input v-model="form.pjGB" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProject">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 项目列表 -->
    <el-table
      :data="paginatedList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      border
      stripe
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="pjName" label="项目名称" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="pjGB" label="标准编号（含年号）" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column fixed="right" label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="viewDetails(scope.row)"
            class="action-button"
          >
            <i class="el-icon-view"></i> 查看
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="deleteRow(scope.row)"
            class="action-button delete"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredList.length"
        background
      >
      </el-pagination>
    </div>

    <!-- 添加隐藏的文件输入框 -->
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      accept=".xlsx,.xls"
      @change="handleFileChange"
    />
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      staId: '',
      staName: '',
      searchKeyword: "",
      projectList: [],
      dialogVisible: false,
      form: {
        pjName: "",
        pjGB: "",
      },
      formLabelWidth: "120px",
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
    };
  },
  created() {
    // 优先使用路由参数，如果没有则使用localStorage中存储的值
    const { param, standardName } = this.$route.params;
    
    // 先尝试从路由参数获取
    this.staId = param;
    this.staName = standardName;

    // 如果路由参数为空，则尝试从localStorage获取
    if (!this.staId) {
      this.staId = localStorage.getItem('staId');
    }
    if (!this.staName) {
      this.staName = localStorage.getItem('standardName');
    }

    // 如果仍然为空，则使用默认值
    if (!this.staName) {
      this.staName = '未知标准';
      console.warn('未能获取到标准名称');
    }
    
    // 更新localStorage
    localStorage.setItem('staId', this.staId);
    localStorage.setItem('standardName', this.staName);

    // 获取项目列表
    if (this.staId) {
      this.fetchProjectList();
    } else {
      this.$message.warning('未能获取到标准ID');
    }
  },
  computed: {
    filteredList() {
      if (!this.searchKeyword) {
        return this.projectList;
      }
      return this.projectList.filter(item => {
        return Object.values(item).some(value =>
          String(value).toLowerCase().includes(this.searchKeyword.toLowerCase())
        );
      });
    },
    paginatedList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredList.slice(start, end);
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async batchDelete() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择要删除的项目');
        return;
      }

      try {
        await this.$confirm("此操作将永久删除选中的项目, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 获取选中项的ID列表
        const pjIds = this.multipleSelection.map(item => item.pjId);
        console.log('准备删除的项目IDs:', pjIds);

        // 调用批量删除接口
        const response = await this.$http.delete('/DeleteMoreProject', {
          data: pjIds,
          headers: {
            'Content-Type': 'application/json'
          }
        });

        console.log('删除响应:', response);
        if (response.data === '删除成功') {
          this.$message.success('批量删除成功');
          this.multipleSelection = []; // 清空选中项
          await this.refreshProjectList(); // 刷新项目列表
        } else {
          this.$message.error(response.data || '批量删除失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        } else {
          console.error('批量删除失败:', error);
          this.$message.error('批量删除失败');
        }
      }
    },
    showDialog() {
      this.dialogVisible = true;
    },
    async addProject() {
      try {
        const receivedParam = this.$route.params.param;
        console.log(receivedParam);
        const formData = {
          pjName: this.form.pjName,
          pjGB: this.form.pjGB,
          staId: receivedParam
        };
        
        // 使用 await 等待添加请求完成
        const response = await this.$http.put('/AddProject', formData);
        
        // 处理响应
        console.log(response.data);
        this.dialogVisible = false; // 关闭对话框
        
        // 重置表单
        this.form = {
          pjName: "",
          pjGB: "",
        };
        
        // 添加成功后立即刷新列表
        await this.refreshProjectList();
        
        this.$message({
          message: '添加项目成功',
          type: 'success'
        });
      } catch (error) {
        // 处理错误
        console.error(error);
        this.$message.error('添加项目失败');
      }
    },

    async deleteRow(row) {
      try {
        await this.$confirm("此操作将永久删除该条目, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 发送删除请求
        const result = await this.$http.delete("/DeleteProject", {
          params: {
            pjId: row.pjId
          }
        });

        console.log('删除响应:', result);
        
        // 删除成功后刷新列表
        await this.refreshProjectList();

        this.$message({
          type: "success",
          message: "删除成功!",
        });

      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        } else {
          console.error('删除失败:', error);
          this.$message.error('删除失败，请稍后重试');
        }
      }
    },
    viewDetails(row) {
      this.$router.push({
        name: 'moudle_select',
        params: {
          param: row.pjId,
          projectName: row.pjName,
          standardName: this.staName,
          staId: this.$route.params.param
        }
      });
    },
    exportExcel() {
      try {
        const exportData = this.projectList.map(item => ({
          '序号': item.pjId,
          '项目名称': item.pjName,
          '标准编号（含年号）': item.pjGB
        }));

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(exportData);

        // 设置表头样式
        ws['!cols'] = [
          { wch: 10 },  // 序号列宽
          { wch: 30 },  // 项目名称列宽
          { wch: 25 }   // 标准编号列宽
        ];

        XLSX.utils.book_append_sheet(wb, ws, "项目列表");
        
        const timestamp = new Date().toISOString().split('T')[0].replace(/-/g, '');
        XLSX.writeFile(wb, `项目列表_${timestamp}.xlsx`);
        
        this.$message({
          message: 'Excel导出成功！',
          type: 'success'
        });
      } catch (error) {
        console.error('Excel导出失败：', error);
        this.$message.error('Excel导出失败，请稍后重试');
      }
    },
    importExcel() {
      this.$refs.fileInput.click();
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet);

          // 转换数据格式
          const receivedParam = this.$route.params.param;
          const formattedData = jsonData.map(item => ({
            pjName: item['项目名称'],
            pjGB: item['标准编号（含年号）'],
            staId: receivedParam
          }));

          // 发送到服务器
          this.uploadExcelData(formattedData);
        } catch (error) {
          console.error('Excel解析失败：', error);
          this.$message.error('Excel解析失败，请检查文件格式');
        }
      };
      reader.readAsArrayBuffer(file);
      // 重置文件输入以允许重复选择同一文件
      e.target.value = '';
    },
    async uploadExcelData(data) {
      try {
        const response = await this.$http.post('/ImportProjects', data);
        this.$message.success('Excel导入成功！');
        // 刷新项目列表
        this.refreshProjectList();
      } catch (error) {
        console.error('Excel导入失败：', error);
        this.$message.error('Excel导入失败，请稍后重试');
      }
    },
    async refreshProjectList() {
      const receivedParam = this.$route.params.param;
      try {
        const result = await this.$http.get("/host/project", {
          params: { staId: receivedParam }
        });
        // 更新列表数据
        this.projectList = result.data;
        // 重置分页到第一页
        this.currentPage = 1;
      } catch (error) {
        console.error('刷新列表失败：', error);
        this.$message.error('刷新列表失败');
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleBack() {
      // 返回时清除相关存储
      localStorage.removeItem('projectId');
      localStorage.removeItem('projectName');
      this.$router.push('/dashboard/dash');
    },
    async fetchProjectList() {
      try {
        const result = await this.$http.get("/host/project", {
          params: { staId: this.staId }
        });
        this.projectList = result.data;
      } catch (error) {
        console.error("获取项目列表失败:", error);
        this.$message.error("获取项目列表失败");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-buttons-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.search-buttons-container .el-input {
  width: 300px;
}

.button-group {
  display: flex;
  gap: 12px;
}

.action-button {
  padding: 4px 8px;
  margin: 0 4px;
  
  &.delete {
    color: #f56c6c;
    background: transparent !important;
    
    &:hover {
      color: #ff4949;
      background-color: transparent !important;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f0f9ff !important;
}

/* 按钮悬浮效果 */
.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 搜索框样式 */
:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.nav {
  padding: 20px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-link {
  text-decoration: none;
  color: #909399;  /* 非当前页面使用灰色 */
  font-size: 16px;
  transition: color 0.3s;  /* 添加颜色过渡效果 */
}

.nav-link:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav span {
  color: #909399;  /* 分隔符使用灰色 */
  font-size: 16px;
  margin: 0 5px;
}

.current-page {
  color: #409EFF !important;  /* 当前页面使用蓝色 */
  font-weight: 500;  /* 当前页面加粗 */
}

.nav-back {
  position: absolute;
  right: 20px;
}

.nav-back .el-button {
  font-size: 14px;
  color: #909399;  /* 返回按钮使用灰色 */
}

.nav-back .el-button:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav-back i {
  margin-right: 5px;

}

:deep(.el-button--text) {
  background: transparent !important;
  
  &:hover, &:focus {
    background: transparent !important;
  }
}
</style>
